<?php
/*
 * Created on Dec 22, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 define("max_chat_per_chatsession",15,true);

 //chat links
$chat_prefix = $index_page . "?chat=";
	$chat_trysendchat = $chat_prefix . "trysendchat";
	$chat_tryrefreshchat = $chat_prefix . "tryrefreshchat";
	
 	//select a single record from chatlog table
	//returns $chat
	function selectSingleFromChatlog($what,$whereKey,$whereVal,$otherConds=""){
		$result = select($what,table_chatlog,$whereKey,$whereVal,$otherConds);
		return $result[0];
	}
	
	function insertIntoChatlog($username,$chatdata,$issession){
		$time=time();
		$chatdata=mysql_real_escape_string($chatdata);
		$query="INSERT INTO `".table_chatlog."` ".
			"(`username`, `chatdata`, `time`, `issession`) ".
			"VALUES ('$username', '$chatdata','$time','$issession');";
		$result=mysql_query($query);
		if($result){
			return mysql_insert_id();
		} else {
			return false;
		}
	}
	
	//is $chat is a session? (or conversation?)
	function isSession(&$session){
		if($session['issession']=="1"){
			return true;
		} else {
			return false;
		}
	}
	
	function updateChatlog($chatid,$updateItem,$updateValue){
		return updateSingleField(table_chatlog,"id",$chatid,$updateItem,$updateValue);
	}
	
	function updateChatdata(&$chat,$newchatdata){
		$newchatdata=mysql_real_escape_string($newchatdata);
		return updateChatlog($chat['id'],"chatdata",$newchatdata);
	}
	
	function deleteFromChatlog($chatid){
		$result = delete(table_chatlog,"id",$chatid);
		return $result;
	}
	
	/*
	function getChatsGreaterThanId($id){
		$table=table_chatlog;
		$what="*";
		$where="WHERE `id`>$id";
		$query = "SELECT $what from `$table` $where;";
	}
	*/
	
	//$id_array -> $chatlog
	function getChatsByIds($id_array){
		$result = select("*",table_chatlog,"id",$id_array,"ORDER BY `id`");
		return $result;
	}
	
	function getChatById($id){
		$result = selectSingleFromChatlog("*","id",$id);
		return $result;
	}
	
	function getSessionChatdataCount(&$chat){
		$chatdata=$chat['chatdata'];
		if($chatdata){
			$chatdata=explode(";",$chatdata);
			return count($chatdata);
		} else {
			return 0;
		}
	}

	function createNewChatSession(&$username=null,$sessiondata=null){
		$chatid=insertIntoChatlog($username,$sessiondata,1);
		return $chatid;
	}
	
	function createNewMessage(&$username, $message){
		return insertIntoChatlog($username,$message,0);
	}
	
	function insertNewMessageIntoSession(&$username,$sessionid,$message){
		$session=getChatById($sessionid);
		if(isSession($session)){
			$msgid=createNewMessage($username,$message);
			
			$chat=getChatById($msgid);
		
			$chatids=$session['chatdata'];
			$chatids=explode(";",$chatids);
			if(getSessionChatdataCount($session)==max_chat_per_chatsession){
				$tobedeleted=array_shift($chatids);
				$chatids[]=$msgid;
				$result = deleteFromChatlog($tobedeleted);
			} else {
				if($chatids[0]==null){
					$chatids[0]=$msgid;
				} else {
					$chatids[]=$msgid;	
				}
				
			}
			//update chat session
			$chatids=implode(";",$chatids);
			$result = updateChatdata($session,$chatids);
		} else{ 
			return false;
		}
	}
	
	function retrieveChatsFromChatsession(&$session,$greater_than_id=0){
		$chatids=$session['chatdata'];
		
		$chatids=explode(";",$chatids);
		if(isset($chatids) && $chatids){
			foreach($chatids as $chatid){
				if ((isset($chatid) && $chatid)){
					if($chatid>$greater_than_id){
						$toberetrieved[]=$chatid;
					}
				}
			}
			if(isset($toberetrieved) && $toberetrieved){
				$chats=getChatsByIds($toberetrieved);
			}
		}
		if(isset($chats) && $chats){
			return $chats;
		}else{
			return false;
		}
	}
	
	function composeChatResponse($sessionid,&$lastchatid){
		$session=getChatById($sessionid);
		if(isset($session) && $session){
			if(isSession($session)){
				$chatids=$session['chatdata'];
				$chatids_exploded=explode(";",$chatids);
				if(isset($chatids) && $chatids){
					$endid=end($chatids_exploded);
					//if ($lastchatid==0){
					//	$lastchatid=$endid;
					//} else {
						if($endid>$lastchatid){
							$chats=retrieveChatsFromChatsession($session,$lastchatid);
							if(isset($chats) && $chats){
								
								foreach($chats as $chat){
									$chatid=$chat['id'];
									if ($chatid>$lastchatid){
										$newlastchatid=$chatid; //update lastchatid
										$chatdata=$chat['chatdata'];
										
										$chatusernick=$chat['username'];

										$chattime=$chat['time'];
										$composedchat[]="$chatid::$chatusernick::$chattime::$chatdata";
									} 
								} 
								$lastchatid=$newlastchatid;
								if (isset($composedchat)){
									$result=implode(";;",$composedchat);
									return $result;
								}
							}
						}
					//}
				}
			}
		}
		return false;
	}
	
	//print the chat html components in page
	function printChat($id="chat"){
		echo "<div id=$id class=marginauto>
					<!--chat ajax injection-->
					<div id=createchat>
					<div id=chatinputwrap>
						<table cellpadding=0 cellspacing=0><tr><td>
							<input id=chatinput type=text>
						</td><td>
							<div id=send>Say!</div>
						</td></tr></table>
					</div></div>
					<div id=chatarea>
						<div id=chatloading loadstatus=0>
							Loading messages ...
						</div>
					</div>
				</div>";
	}

	function printChatInitializeScript($divid,$sessionid,$username){
		global $chat_trysendchat;
		global $chat_tryrefreshchat;
		$chatupdateurl="\"$chat_trysendchat&chatid=$sessionid&username=$username\"";
		$chatrefreshurl="\"$chat_tryrefreshchat&chatid=$sessionid&username=$username\"";
		
		$initialize = "initializeChat($chatupdateurl,$chatrefreshurl,'$divid')";
		echo "<script type='text/javascript'>";
		echo "\$(document).ready($initialize);";
		echo "</script>";
	}

if (isset($_GET['chat'])){
	$chataction = $_GET['chat'];
	
	switch($chataction){
		case 'trysendchat':
			if (isset($_GET['username']) && $_GET['username']){
				$username=urldecode($_GET['username']);
			} else {
				$username="Anon";
			}
			$sessionid=$_GET['chatid'];
			if ($sessionid){
				$message=$_POST['message'];
				if($message){
					//$message=mysql_real_escape_string(urldecode($message));
					$result=insertNewMessageIntoSession($username,$sessionid,$message);
				}
			}
			
			$page=page_ajax;
			break;
			
		case 'tryrefreshchat': //this is an ajax request to retrieve new chatids in chatlog table
			if(isset($_GET['chatid']) && isset($_GET['lastchat'])){
				$sessionid=$_GET['chatid'];
				$lastchatid=$_GET['lastchat'];
				if ($sessionid){
					$responses=composeChatResponse($sessionid,$lastchatid); //$lastchatid is updated here.
					echo "chatresponse=\"".$responses."\";";
					echo "lastchatid=$lastchatid;";
				} else {
					echo "chatresponse=null;";
				}
			}
			$page=page_ajax; //set page to ajax so that page.php won't print anything
			break;
	}
}
?>
